package com.geeguo.ebuilder.client.controller.system.organization;

import com.geeguo.ebuilder.client.base.core.constants.MessageConstants;
import com.geeguo.ebuilder.client.base.core.constants.VirtualConstants;
import com.geeguo.ebuilder.client.base.security.model.LoginUser;
import com.geeguo.ebuilder.client.base.security.utils.AuthUtils;
import com.geeguo.ebuilder.client.base.tenant.model.DataContext;
import com.geeguo.ebuilder.client.base.tenant.provider.TenantProvider;
import com.geeguo.ebuilder.client.business.system.organization.model.*;
import com.geeguo.ebuilder.client.business.system.organization.service.OrganizationService;
import com.geeguo.ebuilder.core.common.action.ActionResult;
import com.geeguo.ebuilder.core.common.utils.key.UUIDCheckUtils;
import com.geeguo.ebuilder.core.common.utils.key.UUIDGenerator;
import com.geeguo.ebuilder.core.security.annotation.RequiresLogin;
import com.geeguo.ebuilder.core.security.annotation.RequiresPermissions;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Tag(name = "组织机构信息")
@RestController
public class OrganizationController {

    @Autowired
    private OrganizationService organizationService;

    @Operation(summary = "查询列表")
    @PostMapping("/system/organization/list")
    @RequiresPermissions("System:Organization")
    public ActionResult<List<OrganizationVO>> list() {
        DataContext dataContext = TenantProvider.getDataContext();
        return ActionResult.success(organizationService.list(dataContext));
    }

    @Operation(summary = "保存")
    @PostMapping("/system/organization/save")
    @RequiresPermissions("System:Organization")
    public ActionResult<Boolean> save(@Validated @RequestBody OrganizationCreateDTO dto) {
        LoginUser currentUser = AuthUtils.getLoginUser();
        DataContext dataContext = TenantProvider.getDataContext();
        OrganizationEntity entity = OrganizationConverter.INSTANCE.convert2Entity(dto);
        entity.setId(UUIDGenerator.getId());
        if (!UUIDCheckUtils.check(entity.getParentId())) {
            entity.setParentId(VirtualConstants.PARENT_ID);
            entity.setDepth(1);
        } else {
            entity.setDepth(organizationService.getCached(entity.getParentId(), dataContext).getDepth() + 1);
        }
        entity.setCode(organizationService.generateCode(entity.getParentId(), dataContext));
        entity.setSequence(organizationService.getMaxSequence(entity.getParentId(), dataContext) + 1);
        entity.setTenantCode(dataContext.getTenantCode());
        entity.setCreateTime(new Date());
        entity.setCreateUser(currentUser.getUserId());
        if (organizationService.save(entity, dataContext)) {
            return ActionResult.success();
        }
        return ActionResult.fail();
    }

    @Operation(summary = "根据ID获取信息")
    @GetMapping("/system/organization/get/{id}")
    @RequiresPermissions("System:Organization")
    public ActionResult<OrganizationVO> get(@PathVariable("id") String id) {
        if (UUIDCheckUtils.check(id)) {
            DataContext dataContext = TenantProvider.getDataContext();
            OrganizationEntity entity = organizationService.get(id, dataContext);
            if (entity != null) {
                return ActionResult.success(OrganizationConverter.INSTANCE.convert2VO(entity));
            }
            return ActionResult.fail(MessageConstants.FAIL_DATA_NOT_EXIST);
        }
        return ActionResult.fail(MessageConstants.FAIL_REQUEST_DATA_ERROR);
    }

    @Operation(summary = "更新组织")
    @PostMapping("/system/organization/update")
    @RequiresPermissions("System:Organization")
    public ActionResult<Boolean> update(@Validated @RequestBody OrganizationUpdateDTO dto) {
        LoginUser currentUser = AuthUtils.getLoginUser();
        DataContext dataContext = TenantProvider.getDataContext();
        OrganizationEntity old = organizationService.get(dto.getId(), dataContext);
        if (old != null) {
            OrganizationEntity entity = OrganizationConverter.INSTANCE.convert2Entity(dto);
            if (!UUIDCheckUtils.check(entity.getParentId())) {
                entity.setParentId(VirtualConstants.PARENT_ID);
            }
            entity.setModifyTime(new Date());
            entity.setModifyUser(currentUser.getUserId());
            if (organizationService.update(entity, old, dataContext)) {
                return ActionResult.success(true);
            }
        }
        return ActionResult.fail();
    }

    @Operation(summary = "删除组织")
    @PostMapping("/system/organization/remove")
    @RequiresPermissions("System:Organization")
    public ActionResult<Boolean> remove(@RequestParam("id") String id) {
        if (UUIDCheckUtils.check(id)) {
            DataContext dataContext = TenantProvider.getDataContext();
            if (organizationService.isUsed(id, dataContext)) {
                return ActionResult.fail(MessageConstants.DATA_USED);
            }
            if (organizationService.existsChild(id, dataContext)) {
                return ActionResult.fail(MessageConstants.EXIST_CHILD);
            }
            if (organizationService.remove(id, dataContext)) {
                return ActionResult.success();
            }
        }
        return ActionResult.fail();
    }

    @Operation(summary = "根据ID获取组织路径")
    @GetMapping("/system/organization/getFullPath/{id}")
    @RequiresPermissions("System:Organization")
    public ActionResult<String> getFullPath(@PathVariable("id") String id) {
        if (UUIDCheckUtils.check(id)) {
            DataContext dataContext = TenantProvider.getDataContext();
            return ActionResult.success(organizationService.getFullPath(id, dataContext));
        }
        return ActionResult.fail(MessageConstants.FAIL_REQUEST_DATA_ERROR);
    }

    @Operation(summary = "查询有效组织树，通用方法，登录即可访问")
    @GetMapping("/system/organization/listValidTreeNode")
    @RequiresLogin
    public ActionResult<List<OrgTreeNodeVO>> listValidTreeNode() {
        DataContext dataContext = TenantProvider.getDataContext();
        List<OrgTreeNodeVO> treeNodeList = organizationService.listValidTreeNode(dataContext);
        return ActionResult.success(treeNodeList);
    }
}